import json
import threading
import time
from ._app import WebSocketApp


class WebSocketClient:

    def __init__(self, url, protocols, messageHandler = None):
        self.isConnect = False
        self.url = url
        self.protocols = protocols
        self.ws = None
        self.messageHandler = messageHandler

    def __onMessage(self, ws, message):
        print 'message:', message
        if self.messageHandler:
            self.messageHandler(json.loads(message))

    def __onError(self, ws, error):
        self.isConnect = False
        print "### error ###", error.message

    def __onClose(self, ws):
        self.isConnect = False
        print "### close ###"
        self.__onReconnect()

    def __onOpen(self, ws):
        self.isConnect = True
        print 'open connect ...'
        t = threading.Thread(target=self.__onHb)
        t.setDaemon(True)
        t.start()

    def __onHb(self):
        while 1:
            time.sleep(10)

            if not self.isConnect:
                break
            self.ws.send(json.dumps(
                {'type': 'debug', 'method': 'debug:hb', 'data': 'ping'}))

    def __onReconnect(self):
        while 1:
            time.sleep(10)
            if self.isConnect:
                break
            print 'reconnect ...'
            self.run()

    def run(self):
        self.ws = WebSocketApp(self.url,
                               subprotocols=self.protocols,
                               on_open=self.__onOpen,
                               on_message=self.__onMessage,
                               on_error=self.__onError,
                               on_close=self.__onClose)
        self.ws.run_forever()

    def send(self, message):
        if not self.isConnect:
            print 'connect closed ...'
            return
        self.ws.send(json.dumps(message))


